#import "EaseChatHelper.h"
#import "AppDelegate.h"
#import "M1ShuntVC.h"
#import "M1MessageViewController.h"
static EaseChatHelper *helper = nil;
@implementation EaseChatHelper
+ (instancetype)shareHelper
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[EaseChatHelper alloc] init];
    });
    return helper;
}
- (void)dealloc
{
    [[EMClient sharedClient] removeDelegate:self];
    [[EMClient sharedClient] removeMultiDevicesDelegate:self];
    [[EMClient sharedClient].groupManager removeDelegate:self];
    [[EMClient sharedClient].contactManager removeDelegate:self];
    [[EMClient sharedClient].roomManager removeDelegate:self];
    [[EMClient sharedClient].chatManager removeDelegate:self];
}
- (id)init
{
    self = [super init];
    if (self) {
        [self initHelper];
    }
    return self;
}
- (void)initHelper
{
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient] addMultiDevicesDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].groupManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].contactManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].roomManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
}
- (void)asyncPushOptions
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = nil;
        [[EMClient sharedClient] getPushOptionsFromServerWithError:&error];
    });
}
- (void)asyncGroupFromServer
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[EMClient sharedClient].groupManager getJoinedGroups];
        EMError *error = nil;
        [[EMClient sharedClient].groupManager getJoinedGroupsFromServerWithPage:0 pageSize:-1 error:&error];
        if (!error) {
        }
    });
}
- (void)asyncConversationFromDB
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *array = [[EMClient sharedClient].chatManager getAllConversations];
        [array enumerateObjectsUsingBlock:^(EMConversation *conversation, NSUInteger idx, BOOL *stop){
            if(conversation.latestMessage == nil){
                [[EMClient sharedClient].chatManager deleteConversation:conversation.conversationId isDeleteMessages:NO completion:nil];
            }
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
        });
    });
}
- (BOOL)isFetchHistoryChange{

 
    NSUserDefaults *uDefaults = [NSUserDefaults standardUserDefaults];
    return [uDefaults boolForKey:@"isFetchHistory"];
}
#pragma mark - EMChatManagerDelegate
- (void)didUpdateConversationList:(NSArray *)aConversationList
{
    if ([M1TabBarController instance]) {
        [[M1TabBarController instance] m1_updateUnReadMessage];
    }
    if ([M1TabBarController instance].m1_messageListVC) {
        [[M1TabBarController instance].m1_messageListVC refreshDataSource];
    }
}
- (void)didReceiveMessages:(NSArray *)aMessages
{
    BOOL isRefreshCons = YES;
    for(EMMessage *message in aMessages){
        BOOL needShowNotification = (message.chatType != EMChatTypeChat) ? [self _needShowNotification:message.conversationId] : YES;
        UIApplicationState state = [[UIApplication sharedApplication] applicationState];
        if (needShowNotification) {
#if !TARGET_IPHONE_SIMULATOR
            switch (state) {
                case UIApplicationStateActive:
                    [[M1TabBarController instance] m1_playSound];
                    break;
                case UIApplicationStateInactive:
                    [[M1TabBarController instance] m1_playSound];
                    break;
                case UIApplicationStateBackground:
                    [[M1TabBarController instance] m1_showMessageNotification:message];
                    break;
                default:
                    break;
            }
#endif
        }
        M1MessageViewController *m1_chatVC ;
        m1_chatVC = [self _getCurrentChatView];
        [[EaseDataBase sharedDataBase] addMessage:message.conversationId uid:[message.ext m1_stringKey:@"uid"] name:[message.ext m1_stringKey:@"nick_name"] avatar:[message.ext m1_stringKey:@"headphoto"]];
        BOOL isChatting = NO;
        if (m1_chatVC) {
            isChatting = [message.conversationId isEqualToString:m1_chatVC.conversation.conversationId];
        }
        if (m1_chatVC == nil || !isChatting || state == UIApplicationStateBackground) {
            [self _handleReceivedAtMessage:message];
            if ([M1TabBarController instance].m1_messageListVC) {
                [[M1TabBarController instance].m1_messageListVC refresh];
            }
            if ([M1TabBarController instance]) {
                [[M1TabBarController instance] m1_updateUnReadMessage];
            }
            return;
        }
        if (isChatting) {
            isRefreshCons = NO;
        }
    }
    if (isRefreshCons) {
        [[M1TabBarController instance].m1_messageListVC refresh];
        [[M1TabBarController instance] m1_updateUnReadMessage];
    }
}
- (void)cmdMessagesDidReceive:(NSArray *)aCmdMessages {

    for (EMMessage *message in aCmdMessages) {
        EMCmdMessageBody *body = (EMCmdMessageBody *)message.body;
        NSDictionary *dict = message.ext;
        if ([body.action isEqualToString:@"logout"]) {
            [M1Alert m1_alertWithTitle:nil message:[dict m1_stringKey:@"alert"] buttonTitles:@[@"确定"] action:^(NSInteger index) {
                [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
                M1ShuntVC *m1_shunVC = [M1ShuntVC new];
                M1NavigationController *m1_nav = [[M1NavigationController alloc]initWithRootViewController:m1_shunVC];
                [UIApplication sharedApplication].delegate.window.rootViewController = m1_nav;
            }];
            break;
        }
    }
}
- (void)messagesDidRecall:(NSArray *)aMessages
{
    for (EMMessage *msg in aMessages) {
        NSString *text;
        if ([msg.from isEqualToString:[EMClient sharedClient].currentUsername]) {
            text = [NSString stringWithFormat:NSLocalizedString(@"message.recall", @"You recall a message")];
        } else {
            text = [NSString stringWithFormat:NSLocalizedString(@"message.recallByOthers", @"%@ recall a message"),msg.from];
        }
        EMMessage *message = [EaseSDKHelper getTextMessage:text to:msg.conversationId messageType:msg.chatType messageExt:@{@"em_recall":@(YES)}];
        message.isRead = YES;
        [message setTimestamp:msg.timestamp];
        [message setLocalTime:msg.localTime];
        EMConversationType conversatinType = EMConversationTypeChat;
        switch (msg.chatType) {
            case EMChatTypeChat:
                conversatinType = EMConversationTypeChat;
                break;
            case EMChatTypeGroupChat:
                conversatinType = EMConversationTypeGroupChat;
                break;
            case EMChatTypeChatRoom:
                conversatinType = EMConversationTypeChatRoom;
                break;
            default:
                break;
        }
        EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:msg.conversationId type:conversatinType createIfNotExist:NO];
        NSDictionary *dict = msg.ext;
        if (dict && [dict objectForKey:@"em_at_list"]) {
            NSArray *atList = [dict objectForKey:@"em_at_list"];
            if ([atList containsObject:[EMClient sharedClient].currentUsername]) {
                NSMutableDictionary *conversationExt = conversation.ext ? [conversation.ext mutableCopy] : [NSMutableDictionary dictionary];
                [conversationExt removeObjectForKey:kHaveUnreadAtMessage];
                conversation.ext = conversationExt;
            }
        }
        [conversation insertMessage:message error:nil];
    }
    [[M1TabBarController instance].m1_messageListVC refresh];
    [[M1TabBarController instance] m1_updateUnReadMessage];
}
#pragma mark - private
- (BOOL)_needShowNotification:(NSString *)fromChatter
{
    BOOL ret = YES;
    NSArray *igGroupIds = [[EMClient sharedClient].groupManager getGroupsWithoutPushNotification:nil];
    for (NSString *str in igGroupIds) {
        if ([str isEqualToString:fromChatter]) {
            ret = NO;
            break;
        }
    }
    return ret;
}
- (EaseMessageViewController*)_getCurrentChatView
{
    NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:[M1TabBarController instance].navigationController.viewControllers];

    M1MessageViewController *chatViewContrller = nil;
    for (id viewController in viewControllers)
    {
        if ([viewController isKindOfClass:[M1MessageViewController class]])
        {
            chatViewContrller = viewController;
            break;
        }
    }
    return chatViewContrller;
}
- (void)_handleReceivedAtMessage:(EMMessage*)aMessage
{
    if (aMessage.chatType != EMChatTypeGroupChat || aMessage.direction != EMMessageDirectionReceive) {
        return;
    }
    NSString *loginUser = [EMClient sharedClient].currentUsername;
    NSDictionary *ext = aMessage.ext;
    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:aMessage.conversationId type:EMConversationTypeGroupChat createIfNotExist:NO];
    if (loginUser && conversation && ext && [ext objectForKey:kGroupMessageAtList]) {
        id target = [ext objectForKey:kGroupMessageAtList];
        if ([target isKindOfClass:[NSString class]] && [(NSString*)target compare:kGroupMessageAtAll options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            NSNumber *atAll = conversation.ext[kHaveUnreadAtMessage];
            if ([atAll intValue] != kAtAllMessage) {
                NSMutableDictionary *conversationExt = conversation.ext ? [conversation.ext mutableCopy] : [NSMutableDictionary dictionary];
                [conversationExt removeObjectForKey:kHaveUnreadAtMessage];
                [conversationExt setObject:@kAtAllMessage forKey:kHaveUnreadAtMessage];
                conversation.ext = conversationExt;
            }
        }
        else if ([target isKindOfClass:[NSArray class]]) {
            if ([target containsObject:loginUser]) {
                if (conversation.ext[kHaveUnreadAtMessage] == nil) {
                    NSMutableDictionary *conversationExt = conversation.ext ? [conversation.ext mutableCopy] : [NSMutableDictionary dictionary];
                    [conversationExt setObject:@kAtYouMessage forKey:kHaveUnreadAtMessage];
                    conversation.ext = conversationExt;
                }
            }
        }
    }
}
- (void)userAccountDidLoginFromOtherDevice{
    [M1Alert m1_alertWithTitle:nil message:@"您的账号在其他设备登录，若非本人操作请及时检查。" buttonTitles:@[@"确定"] action:^(NSInteger index) {
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
        M1ShuntVC *m1_shunVC = [M1ShuntVC new];
        M1NavigationController *m1_nav = [[M1NavigationController alloc]initWithRootViewController:m1_shunVC];
        [UIApplication sharedApplication].delegate.window.rootViewController = m1_nav;
    }];
    
}
@end
